<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>BuildingAI - RunChat - HTML Renderer</title>
    <style>
        html,
        body {
            margin: 0;
            padding: 0;
            width: 100%;
            height: 100%;
            overflow: hidden;
        }
    </style>
</head>

<body>
    <script>
        (function () {
            const trustedOrigins = [
                window.location.origin,
                'http://localhost:4090',
                'http://localhost:4091'
            ];

            function setupMessageListener() {
                window.addEventListener('message', function handleMessage(event) {
                    const origin = event.origin;

                    if (!trustedOrigins.includes(origin)) {
                        console.warn('⚠️ Ignoring message from untrusted origin:', origin);
                        return;
                    }

                    const data = event.data;

                    if (!data || !data.BuildingAICode) {
                        return;
                    }

                    const htmlCode = data.BuildingAICode;


                    const keys = Object.keys(data)
                    if (keys.length !== 1) return
                    if (!data.BuildingAICode) return
                    document.open()
                    document.write(data.BuildingAICode)
                    document.close()
                    const style = document.createElement('style')
                    style.textContent = 'body { margin: 0; }'
                    const firstStyle = document.head.querySelector('style')
                    if (firstStyle) {
                        document.head.insertBefore(style, firstStyle)
                    } else {
                        document.head.appendChild(style)
                    }
                }, true);
            }

            function extractTitle(htmlCode) {
                var match = htmlCode.match(/<title[^>]*>([^<]+)<\/title>/i);
                return match ? match[1].trim() : '';
            }

            setupMessageListener();

            window.addEventListener('load', () => {
                window.parent.postMessage({ iframeLoaded: true }, '*');
            });
        })();
    </script>
</body>

</html>